<?php

namespace App\Http\Controllers\Agent;

use App\Exceptions\OrException;
use App\Service\UserService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\GuildUser;

class LoginController extends Controller
{
    public $v = 'agent.login.';



    public function index()
    {
        if (Auth::check())
        {

             return redirect()->route('agent_index');
        }

        return view($this->v . 'agent_login');
    }

    public function signIn(Request $request, UserService $userService)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'code' => 'required|captcha',
        ],[
            'code.captcha' => '验证码错误',
        ]);
        $error = $validator->errors()->first();
        if ($error) return ajaxError($error);
        $remeber = $request->filled('remember') ? true : false;
        $this->agent_auth($request->username, $request->password, $remeber);
        return ajaxSuccess();
    }

    /**
     * @param string $username
     * @param string $password
     * @param bool $remember
     * @throws OrException
     */
    public function agent_auth(string $username, string $password, bool $remember)
    {
        $guildUser = GuildUser::where('username', $username)->first();
        $error = '用户名或密码错误';
        if (null === $guildUser) throw new OrException($error);
        if (GuildUser::NOT_ACTIVE === $guildUser->status) throw new OrException($error);
        $res = password_verify($password, $guildUser->password);
        if ($res === false) throw new OrException($error);
        Auth('agent')->login($guildUser, $remember);
        (new GuildUser())->cacheRules($guildUser->id);
    }

    public function logOut()
    {
        Auth::guard('agent')->logout();
        return redirect()->route('agent/login');
    }

}
